<?php

namespace app\admin\dao;

use app\common\model\Area;
use ShidianUtil\Thinkphp\Dao\DaoTrait;
use think\facade\Cache;
use think\facade\Config;

/**
 * AreaDao 数据访问对象
 * Class AreaDao
 * @package app\dao
 * @method Area findByPK(?int $id, $field = true)
 * @method \think\Collection selectAll(?int $page, ?int $page_size, $field = true)
 * @method Area insertActive(array $params, array $allow_field = [])
 * @method Area updateActive(Area $model, array $params, array $allow_field = [])
 * @method Area findAndUpdateActive(int $id, array $params, array $allow_field = [])
 * @method Area updateActiveByClosure(\Closure $closure, array $params, array $allow_field = [])
 * @method void deleteModel(Area $model)
 * @method void deleteById(int|array|\Closure $id, bool $force = false)
 * @link https://www.kancloud.cn/manual/thinkphp6_0/1037579
 * @link https://www.kancloud.cn/manual/think-orm/1257998
 * @link https://www.kancloud.cn/thinkphp/master-database-and-model/265551
 */
class AreaDao
{
    private $ttl;

    use DaoTrait;

    /**
     * @var \app\common\model\Area
     */
    private $baseModel;

    /**
     * AreaDao constructor.
     */
    public function __construct()
    {
        $this->baseModel = Area::class;
        $this->ttl = Config::get('querycache.area.ttl', 24 * 3600);
    }

    public function selectCities()
    {
        // 添加缓存
        $key = AreaDao::class . ':selectCities';

        $data = Cache::get($key, null);

        if (is_null($data) || empty($data)) {

            $data = $this->selectCities0()->toArray();

            Cache::set($key, $data, $this->ttl);
        }

        return $data;
    }

    private function selectCities0()
    {
        return Area::with([
                'children' => fn($query) => $query->cascader()
            ])
            ->cascader()
            ->where('pid', 0)
            ->where('status', 0)
            ->select();
    }

}
